#include "mainwindow.h"
#include <QLayout>
#include "CustomImageView.h"
#include <QPushButton>
#include <QFileDialog>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QGraphicsPixmapItem>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , m_pImageView(Q_NULLPTR)
    , m_pOpenImageBtn(Q_NULLPTR)
{
    this->resize(500,500);
    if(false == InitWidget())
    {
        throw std::bad_alloc();
    }
}

MainWindow::~MainWindow()
{

}

bool MainWindow::InitWidget()
{
    //初始化控件

    //窗口命名
    setWindowTitle("图片查看器");
    m_pImageView = new CustomImageView(this);
    m_pOpenImageBtn = new QPushButton(this);
    m_pOpenImageBtn->setText("OpenImage");

    //初始化信号槽
    connect(m_pOpenImageBtn,&QPushButton::clicked,this,&MainWindow::OnOpenButtonClicked);

    //初始化布局
    QHBoxLayout* pButtonLayout = new QHBoxLayout();
    pButtonLayout->setContentsMargins(0,0,0,0);
    pButtonLayout->setSpacing(0);
    pButtonLayout->addWidget(m_pOpenImageBtn);
    pButtonLayout->addStretch();

    QVBoxLayout* pMainLayout = new QVBoxLayout();
    pMainLayout->setContentsMargins(0,0,0,0);
    pMainLayout->setSpacing(0);
    pMainLayout->addWidget(m_pImageView);
    pMainLayout->addLayout(pButtonLayout);

    QWidget* pCenterWidget = new QWidget(this);
    pCenterWidget->setLayout(pMainLayout);

    this->setCentralWidget(pCenterWidget);

//    //创建Scene
//    QGraphicsScene* pScene = new QGraphicsScene(this);
//    //创建View并为其绑定Scene
//    QGraphicsView* pView = new QGraphicsView(this);
//    pView->setScene(pScene);
//    //使用我们的图像初始化一个Item
//    QImage srcImage("C:\\Users\\Administrator\\Pictures\\Laner\\Laner.png");
//    QGraphicsPixmapItem* pItem = new QGraphicsPixmapItem();
//    //设置元素可以选中和拖动
//    pItem->setAcceptHoverEvents(true);
//    pItem->setFlags(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsMovable);
//    pItem->setPixmap(QPixmap::fromImage(srcImage));
//    pScene->addItem(pItem);

//    //将我们上面实现的View添加到主界面
//    QVBoxLayout* pMainLayout = new QVBoxLayout();
//    pMainLayout->setContentsMargins(0,0,0,0);
//    pMainLayout->setSpacing(0);
//    pMainLayout->addWidget(pView);

//    QWidget* pCenterWidget = new QWidget(this);
//    pCenterWidget->setLayout(pMainLayout);

//    this->setCentralWidget(pCenterWidget);

    return true;
}

void MainWindow::OnOpenButtonClicked()
{
    QString fileName = QFileDialog::getOpenFileName(
                this,
                "open image",
                "/D:/",
                "Image Files(*.png .jpg .bmp)");
    QImage srcImage = QImage(fileName);
    m_pImageView->OnSendImage(srcImage);
}

